const utils = require('./utils');
const path = require("path");
const { mdToPdf } = require('md-to-pdf');
const fs = require('fs');
const chalk = require('chalk');
const escapeStringRegexp = require('escape-string-regexp');

async function parse(md, options ) {
    // const filename =  path.basename(md.path, '.md');
    // console.log(md.meta.data);
    let {title, date, categories = ['']} = md.meta.data;

    if(!categories) {
        console.log(chalk.red(`忽略<${md.path}>`));
        return md;
    }

    title = title.replace(/\//g, '-');

    console.log(chalk.greenBright(`正在转换<${md.path}>`));

    const pdf = await mdToPdf({ path: md.path, basedir: `${utils.rootPath}/md` }).catch(console.error);

    if (pdf) {
        const categoryLink = categories.join('_');
        fs.writeFileSync(`${options.pdfPath}/${categoryLink}_${title}.pdf`, pdf.content);
    }

    return pdf;
}

module.exports = {
    parse
}
